/*
 * Copyright 2011 evswork Team
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

package org.evswork.getwit;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.preference.PreferenceManager;

public class TweetObject{
	String content;
	String user;
	long id;
	int flag;
	Context ctxt;
	boolean recent;
	
	// mark if this object is not a tweet
	public final static int NORMAL = 0;
	public final static int NOT_TWEET = 1;
	public final static int MENTION = 2;
	public final static int MY_TWEET = 3;
	
	public static String getUser(String rawdata) {
		Pattern pattern = Pattern.compile(
				"(?:用户个人信息\n\n用户名： |User Profile:\n\nUsername: )([_0-9a-zA-Z]+)\n\n",
				Pattern.DOTALL);
		Matcher matcher = pattern.matcher(rawdata);
		if (matcher.find()) {
			return matcher.group(1);
		} else {
			return null;
		}
	}
	
	public static String makeDummyUserData(Context ctxt,String u) {
		return String.format("用户个人信息\n\n用户名： %s\n\n(暂无结果)", u);
	}
	
	private int getFlag() {
		String myname =PreferenceManager.getDefaultSharedPreferences(ctxt)
				.getString("screen_name", "").toLowerCase();
		if (id == 0) {
			return NOT_TWEET;
		}
		if (user.equalsIgnoreCase(myname)) {
			return MY_TWEET;
		}
		if (content.toLowerCase().contains(myname)) {
			return MENTION;
		}
		return NORMAL;
	}
	
	@Override
	public boolean equals(Object o) {
		TweetObject t;
		String a,b;
		try {
			t= (TweetObject)o;
			if (t.flag == NOT_TWEET) {
				a = getUser(content);
				b = getUser(t.content);
				if (a != null && b != null)
				{
					return a.equalsIgnoreCase(b);
				} else
					return t.content.equals(this.content);
			}
			return t.id == this.id;
		} catch (Exception e) {
			return false;
		}
	}

	TweetObject(Context ctxt,String content,String user,long id) {
		this.ctxt = ctxt;
		this.content = content;
		this.user = user;
		this.id = id;
		this.flag=getFlag();
		this.recent = true; // mark this tweet as 'recent'
	}
	
	TweetObject(Context ctxt,int flag) {
		// create a sample
		this.ctxt = ctxt;
		this.flag = flag;
		String [] array = ctxt.getResources().getStringArray(R.array.tweet_type);
		this.id = 0;
		this.content = array[flag];
		this.user = array[flag];
		this.recent = false; // not necessary
	}
}
